﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace NineMine.Core
{
    public class HashHelper :IDisposable
    {
        private MD5 _hash;
        public HashHelper()
        {
            _hash = MD5.Create();
        }

        public string GenerateHash(string input)
        {
            // Convert the input string to a byte array and compute the hash. 
            byte[] data = _hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            var builder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
                builder.Append(data[i].ToString("x2"));

            // Return the hexadecimal string. 
            return builder.ToString();
        }

        public string GenerateHash(Stream input)
        {
            // Convert the input string to a byte array and compute the hash. 
            byte[] data = _hash.ComputeHash(input);

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            var builder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
                builder.Append(data[i].ToString("x2"));

            // Return the hexadecimal string. 
            return builder.ToString();
        }

        public bool VerifyHashMatch(string input, string hash)
        {
            // Hash the input. 
            var inputHash = GenerateHash(input);

            // Create a StringComparer an compare the hashes.
            var comparer = StringComparer.OrdinalIgnoreCase;

            return 0 == comparer.Compare(inputHash, hash);
        }

        public bool VerifyHashMatch(Stream input, string hash)
        {
            // Hash the input. 
            var inputHash = GenerateHash(input);

            // Create a StringComparer an compare the hashes.
            var comparer = StringComparer.OrdinalIgnoreCase;

            return 0 == comparer.Compare(inputHash, hash);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _hash.Dispose();
            }
        }
    }
}
